﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using DotNetOpenAuth.OAuth;
using DotNetOpenAuth.Messaging;
using OAuth;
using System.Data;
using System.Net;
using System.Xml;

namespace G.SharePoint.Yammer
{
    public partial class YammerPage : LayoutsPageBase
    {
        protected string consumerKey = "B2peLENOjRH1qEZ8skWBg";
        protected string consumerSecret = "dtI0YpshyXcJA8yaojytIFFaGnoNHoziEy3dpauZkr0";
       // protected string requestServer = "http://api.myspace.com";

        private string RequestToken
        {
            get { return (string)ViewState["YammerRequestToken"]; }
            set { ViewState["YammerRequestToken"] = value; }
        }

        private string AccessToken
        {
            get { return (string)Session["YammerAccessToken"]; }
            set { Session["YammerAccessToken"] = value; }
        }

        private InMemoryTokenManager TokenManager
        {
            get
            {
                var tokenManager = (InMemoryTokenManager)Application["YammerTokenManager"];
                if (tokenManager == null)
                {
                  //  string consumerKey = ConfigurationManager.AppSettings["YammerConsumerKey"];
                  //  string consumerSecret = ConfigurationManager.AppSettings["YammerConsumerSecret"];
                    if (!string.IsNullOrEmpty(consumerKey))
                    {
                        tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret);
                        Application["YammerTokenManager"] = tokenManager;
                    }
                }

                return tokenManager;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.TokenManager != null)
            {
                this.MultiView1.SetActiveView(this.BeginAuthorizationView);
            }
        }

        protected void getYammerMessages_Click(object sender, EventArgs e)
        {
            var yammer = new WebConsumer(YammerConsumer.ServiceDescription, this.TokenManager);
        }

        protected void obtainAuthorizationButton_Click(object sender, EventArgs e)
        {
            var yammer = YammerConsumer.CreateConsumer(this.TokenManager);
            string requestToken;
            Uri popupWindowLocation = YammerConsumer.PrepareRequestAuthorization(yammer, out requestToken);
            this.RequestToken = requestToken;
            string javascript = "window.open('" + popupWindowLocation.AbsoluteUri + "');";
            this.Page.ClientScript.RegisterStartupScript(GetType(), "YammerPopup", javascript, true);
            this.MultiView1.SetActiveView(this.CompleteAuthorizationView);
        }

        protected void finishAuthorizationButton_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }

            var yammer = YammerConsumer.CreateConsumer(this.TokenManager);
            var authorizationResponse = YammerConsumer.CompleteAuthorization(yammer, this.RequestToken, this.yammerUserCode.Text);
            if (authorizationResponse != null)
            {
                this.accessTokenLabel.Text = HttpUtility.HtmlEncode(authorizationResponse.AccessToken);
                this.MultiView1.SetActiveView(this.AuthorizationCompleteView);
            }
            else
            {
                this.MultiView1.SetActiveView(this.BeginAuthorizationView);
                this.authorizationErrorLabel.Visible = true;
            }
        }

        //public DataSet MakeRequest(string restCall)
        //{
        //    // Form the full REST request url
        //    Uri url = new Uri(requestServer + restCall);
        //    DataSet ds = new DataSet();

        //    // Instantiate OAuthBase and declare variables
        //    OAuthBase oAuth = new OAuthBase();
        //    string nonce = oAuth.GenerateNonce();
        //    string timeStamp = oAuth.GenerateTimeStamp();
        //    string normUrl = string.Empty;
        //    string normParams = string.Empty;
        //    string strRequest = string.Empty;

        //    // Create an OAuth signature
        //    string signature = oAuth.GenerateSignature(url,
        //        consumerKey, consumerSecret, string.Empty, string.Empty,
        //        "GET", timeStamp, nonce, OAuth.OAuthBase.SignatureTypes.HMACSHA1,
        //        out normUrl, out normParams);

        //    // Construct the OAuth authenticated REST url
        //    strRequest = normUrl + "?" + normParams + "&" + Server.UrlEncode("oauth_signature") + "=" + Server.UrlEncode(signature);

        //    return MakeWebRequest(strRequest);
        //}


        //protected DataSet MakeWebRequest(string restCall)
        //{
        //    // Make web request
        //    HttpWebRequest request = WebRequest.Create(restCall) as HttpWebRequest;
        //    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        //    {
        //        // In this example we are getting back XML
        //        XmlTextReader xReader = new XmlTextReader(response.GetResponseStream());

        //        DataSet ds = new DataSet();
        //        ds.ReadXml(xReader);
        //        xReader.Close();

        //        return ds;
        //    }
        //}

        //protected void GetFriendList()
        //{
        //    rptFriends.DataSource = fb.MakeRequest("/v1/users/YOUR_USER_ID/friends.xml?page_size=100");
        //    rptFriends.DataBind();
        //}
    }
}